//
//  LTY_FilmAndSongsTableViewCell.m
//  MooMusic
//
//  Created by 守护神 on 15/10/21.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "LTY_FilmAndSongsTableViewCell.h"
#import "FilmAndSongs.h"
@implementation LTY_FilmAndSongsTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self creatSubviews];
    }
    
    return self;
}

- (void)creatSubviews
{
    _numberLabel = [[UILabel alloc] init];
   // _numberLabel.backgroundColor = [UIColor orangeColor];
    _numberLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_numberLabel];
    
    nameLable = [[UILabel alloc] init];
    //nameLable.backgroundColor = [UIColor cyanColor];
    [self.contentView addSubview:nameLable];
    
    singerNameLabel = [[UILabel alloc] init];
    //singerNameLabel.backgroundColor = [UIColor redColor];
    singerNameLabel.font = [UIFont systemFontOfSize:13];
    [self.contentView addSubview:singerNameLabel];
    
    downLoadButton = [[UIButton alloc] init];
    downLoadButton.backgroundColor = [UIColor brownColor];
    [self.contentView addSubview:downLoadButton];
    
    progressView = [[UIProgressView alloc] init];
    [self.contentView addSubview:progressView];
    
    collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    collectionButton.backgroundColor = [UIColor clearColor];
    [collectionButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang@2x.png"] forState:UIControlStateNormal];
    [collectionButton addTarget:self action:@selector(collectionAction:) forControlEvents:UIControlEventTouchUpInside];
   [self.contentView addSubview:collectionButton];
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [_numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.contentView).with.offset(10);
        make.left.equalTo(self.contentView).with.offset(20);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
        
    }];
    
    
    [nameLable mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.contentView).with.offset(5);
        // 注意:
        make.left.equalTo(_numberLabel.mas_right).with.offset(15);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
        
    }];
    
    
    [singerNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(nameLable.mas_bottom).with.offset(10);
        make.left.equalTo(_numberLabel.mas_right).with.offset(15);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(30);
        
    }];
    

    
    
    [collectionButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.contentView).with.offset(30);
        make.left.equalTo(singerNameLabel.mas_right).with.offset(80);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
        
    }];
    
    
    
    [downLoadButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.contentView).with.offset(30);
        make.left.equalTo(singerNameLabel.mas_right).with.offset(10);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
        
    }];
    
    
    if (self.model.modelSelect) {
        [collectionButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang@2x.png"] forState:UIControlStateNormal];
    } else {
        [collectionButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang@2x.png"] forState:UIControlStateNormal];
    }

    [downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
    
    // 下载按钮触发的方法
    [downLoadButton addTarget:self action:@selector(downLoadAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(collectionButton.mas_bottom).with.offset(3);
        make.left.equalTo(singerNameLabel.mas_right).with.offset(3);
        make.width.mas_equalTo(140);
        make.height.mas_equalTo(3);
        
    }];
    
    
    
}
// 重写model的set方法
- (void)setModel:(LTY_TenSongsModel *)model
{
    _model = model;
    nameLable.text = model.name;
    singerNameLabel.text = model.singerName;
}


// 收藏按钮触发的方法
- (void)collectionAction:(UIButton *)Sender
{
    NSLog(@"5555555555_+_+_+_+_+_+_  %d", self.model.modelSelect);
    Sender.selected = self.model.modelSelect;
    Sender.selected = !Sender.selected;
    self.model.modelSelect = Sender.selected;
    
    if (self.model.modelSelect) {
        NSLog(@"666666666_+_+_+_+_+_+_  %d", self.model.modelSelect);
        NSLog(@"收藏");
        /* 给数据库中添加数据 */
        FilmAndSongs *filmAndSong = [FilmAndSongs MR_createEntity];
        filmAndSong.name = self.model.name;
        filmAndSong.url =  self.urlString;
        [[NSManagedObjectContext MR_defaultContext]MR_saveToPersistentStoreAndWait];
        
        [collectionButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang@2x.png"] forState:
         UIControlStateNormal];
        //
        //        /* 查询数据库中的数据 */
        //        NSMutableArray *findArr = [NSMutableArray array];
        //        findArr = [NSMutableArray arrayWithArray:[FilmAndSongs MR_findAll]];
        //        NSLog(@"_____________%ld",findArr.count);
        
    }else{
        
        NSLog(@"取消收藏");
        NSLog(@"77777777_+_+_+_+_+_+_  %d", self.model.modelSelect);
        /* 删除数据库中的数据 */
        //        NSMutableArray *findArr = [NSMutableArray array];
        //        findArr = [NSMutableArray arrayWithArray:[FilmAndSongs MR_findAll]];
        
        NSArray *songs = [FilmAndSongs MR_findByAttribute:@"name" withValue:self.model.name];
        for (FilmAndSongs *song in songs) {
            [song MR_deleteEntity];
        }
        [collectionButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang@2x.png"] forState:UIControlStateNormal];
        
    }
    
}


#pragma mark -- 下载按钮触发的方法
- (void)downLoadAction:(UIButton *)Sender
{
    Sender.selected = !Sender.selected;
    if (Sender.selected) {
        
        if (self.partialData) {
            [Sender setTitle:@"暂停" forState:UIControlStateNormal];
            //判断是否又已下载数据，有的话就断点续传，没有就完全重新下载
           self.task = [[self session] downloadTaskWithResumeData:self.partialData];
           [self.task resume];
        
        }else{
        
    [Sender setTitle:@"暂停" forState:UIControlStateNormal];
    //用NSURLSession和NSURLRequest创建网络任务
    self.task = [[self session] downloadTaskWithRequest:[self request]];
    [self.task resume];
        }
    
    }else{
    [Sender setTitle:@"下载" forState:UIControlStateNormal];
        NSLog(@"Pause download task");
        if (self.task) {
            //取消下载任务，把已下载数据存起来
            [self.task cancelByProducingResumeData:^(NSData *resumeData) {
                self.partialData = resumeData;
                self.task = nil;
            }];
        }
        
    }
}


#pragma mark -- NSURLSession
- (NSURLSession *)session
{
    //创建NSURLSession
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
    return session;
}

- (NSURLRequest *)request
{
    //创建请求
    NSURL *url = [NSURL URLWithString:self.downLoadString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    return request;
}

//创建文件本地保存目录
-(NSURL *)createDirectoryForDownloadItemFromURL:(NSURL *)location
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSURL *documentsDirectory = urls[0];
    // 改变后缀
    return [[documentsDirectory URLByAppendingPathComponent:[location lastPathComponent]] URLByAppendingPathExtension:@".mp4"];
}
//把文件拷贝到指定路径
-(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination
{
    
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtURL:destination error:NULL];
    [fileManager copyItemAtURL:location toURL:destination error:&error];
    if (error == nil) {
        return true;
    }else{
        NSLog(@"%@",error);
        return false;
    }
}

#pragma mark NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    //下载成功后，文件是保存在一个临时目录的，需要开发者自己考到放置该文件的目录
    NSLog(@"Download success for URL: %@",location.description);
    NSURL *destination = [self createDirectoryForDownloadItemFromURL:location];
    BOOL success = [self copyTempFileAtURL:location toDestination:destination];
    
    if(success){
        //        文件保存成功后，使用GCD调用主线程把文件显示
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"下载成功");
            [downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
            
        });
    }else{
        NSLog(@"Meet error when copy file");
    }
    self.task = nil;
}

/* Sent periodically to notify the delegate of download progress. */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //刷新进度条的delegate方法，同样的，获取数据，调用主线程刷新UI
    double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
      
        NSLog(@"下载进度 = %f", currentProgress);
        //刷新进度条的delegate方法，同样的，获取数据，调用主线程刷新UI
        double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite;
        dispatch_async(dispatch_get_main_queue(), ^{
            progressView.progress = currentProgress;
            progressView.hidden = NO;
        });

    
    });
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}



- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
